package com.mj.mes.system.SysRole;

import com.mj.mes.config.shiro.CheckPermission;
import com.mj.mes.system.SysResource.SysResource;
import com.mj.mes.system.SysResource.SysResourceService;
import com.mj.mes.system.SysUser.SysUser;
import com.mj.mes.utils.BaseBeanDao;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by mj on 2017/3/29.
 */
@Controller
@RequestMapping("role")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysResourceService sysResourceService;

    @Autowired
    private BaseBeanDao baseBeanDao;
    /**
     * 带分页查询
     *
     * @param sysRole
     * @param page
     * @param rows
     * @param size
     * @return
     */
    @RequestMapping("findAllWithPaging")
    @ResponseBody
    @CheckPermission(permission={"role:view"})
    public Map<String, Object> findAllWithPaging(SysRole sysRole, Integer page, Integer rows, @RequestParam(value = "rows") Integer size) {
        Map<String, Object> map = new HashedMap();
        Page<SysRole> list = sysRoleService.findAll(new PageRequest(page - 1, size));
        int total = sysRoleService.findAll().size();
        map.put("total", total);
        map.put("rows", list.getContent());
        return map;
    }

    /**
     * 添加角色
     *
     * @param
     * @return
     */
    @RequestMapping(value = "addRole", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"role:create"})
    public Map<String, Object> addRole(SysRole sysRole) {
        Map<String, Object> map = new HashedMap();
        //默认状态为0
        try {
            sysRole.setRoleAvailable(0);
            sysRoleService.addRole(sysRole);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }

    /**
     * 删除角色
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    @CheckPermission(permission={"role:delete"})
    public Map<String, String> deletRole(String ids) {
        Map<String, String> map = new HashedMap();
        String[] idArrayList = ids.split(",");
        List<SysRole> list = new ArrayList<SysRole>();
        for (int i = 0; i < idArrayList.length; i++) {
            SysRole sysRole = new SysRole();
            sysRole.setId(Long.valueOf(idArrayList[i]));
            SysUser sysUser = new SysUser();
            list.add(sysRole);
        }
        boolean flag = sysRoleService.delete(list);
        if (flag) {
            map.put("msg", "success");
        } else {
            map.put("msg", "fail");
        }
        return map;
    }

    /**
     * 跳转到修改角色界面
     *
     * @param sysRole
     * @param model
     * @return
     */
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    @CheckPermission(permission={"role:update"})
    public String toUpdateRole(SysRole sysRole, Model model) {
        sysRole = sysRoleService.findOne(sysRole.getId());
        model.addAttribute("sysRole", sysRole);
        return "role/roleEdit";
    }

    /**
     * 资源菜单
     *
     * @return
     */
    @RequestMapping("queryResourceByRoleId")
    @ResponseBody
    @CheckPermission(permission={"role:view"})
    public Map findAll(SysRole sysRole) throws JSONException, JsonProcessingException {
        Map listMap = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        sysRole=sysRoleService.findOne(Long.valueOf(sysRole.getId()));
        //该角色拥有的权限
        Set<SysResource> roleOwnSysResource=sysRole.getSysresources();
        //所有的权限集合
        List<SysResource> list = sysResourceService.findAll();
        List arrayList =new ArrayList();
        for ( SysResource sysResource : list){
            Object object  = sysResource ;
            Map arrtMap = new HashMap();
            if(sysResource.getSysResource() != null){
                arrtMap.put("_parentId",sysResource.getSysResource().getId());
            }
            if(roleOwnSysResource.contains(sysResource)){
                arrtMap.put("checked","true");
                arrtMap.put("selected","true");
            }
            object = baseBeanDao.addAttributes(object,arrtMap);
            arrayList.add(object);
        }
        listMap.put("rows",arrayList);
        return listMap;
    }

    /**
     * 改变角色状态
     *
     * @param roleIds
     * @return
     */
    @PostMapping("changeRoleStatus")
    @ResponseBody
    @CheckPermission(permission={"role:update"})
    public Map<String, Object> changeRoleStatus(String roleIds) {
        Map<String, Object> map = new HashedMap();
        List<SysRole> list = new ArrayList<>();
        String[] roleIdArry = roleIds.split(",");
        for (int i = 0; i < roleIdArry.length; i++) {
            SysRole sysRole = sysRoleService.findOne(Long.valueOf(roleIdArry[i]));
            if (sysRole.getRoleAvailable() != null ) {
                //0表示可用
                if (sysRole.getRoleAvailable() == 0) {
                    sysRole.setRoleAvailable(1);
                    //将1设置为0
                } else {
                    sysRole.setRoleAvailable(0);
                }
            } else {
                sysRole.setRoleAvailable(0);//将空设置为0，即可用
            }
            list.add(sysRole);
        }
        try {
            sysRoleService.saveInBanch(list);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }


    /**
     * 设置权限
     *
     * @param ids
     * @return
     */
    @PostMapping("setPerssionForRole")
    @ResponseBody
    @CheckPermission(permission={"role:update"})
    public Map<String, Object> setPerssionForRole(String roleId,String ids) {
        Map<String, Object> map = new HashedMap();
        SysRole sysRole=sysRoleService.findOne(Long.valueOf(roleId));
        //清空权限
        if (ids==null||"".equals(ids)){
            sysRole.setSysresources(null);
            try {
                sysRoleService.addRole(sysRole);
                map.put("msg", "success");
            } catch (Exception e) {
                map.put("msg", "fail");
            }
            return map;
        }
        String[] permissionId=ids.split(",");
        List<Long>permissionIdLists=new ArrayList<Long>();
        for (int i=0;i<permissionId.length;i++){
            permissionIdLists.add(Long.valueOf(permissionId[i]));
        }
        Set<SysResource>sysResourceSet=sysResourceService.findInBacth(permissionIdLists);
        sysRole.setSysresources(sysResourceSet);
        try {
            sysRoleService.addRole(sysRole);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }
    @RequestMapping("updateRole")
    @ResponseBody
    @CheckPermission(permission={"role:update"})
    public Map<String, Object> getSingleRole(SysRole newSysRole){
        Map<String, Object> map = new HashedMap();
        try {
            //数据库原来的role，因为之更改了role的属性，关系没有更改，所以要先查询出来
            SysRole dbSysRole=sysRoleService.findOne(newSysRole.getId());
            dbSysRole.setRoleName(newSysRole.getRoleName());
            dbSysRole.setRoleDescription(newSysRole.getRoleDescription());
            dbSysRole.setRoleAvailable(newSysRole.getRoleAvailable());
            sysRoleService.addRole(dbSysRole);
            map.put("msg", "success");
        } catch (Exception e) {
            map.put("msg", "fail");
        }
        return map;
    }
}
